package com.azusa.xbjy.service.impl;

import com.azusa.xbjy.dao.MeetingDao;
import com.azusa.xbjy.dao.MeetingMapper;
import com.azusa.xbjy.dao.UserMapper;
import com.azusa.xbjy.entity.Meeting;
import com.azusa.xbjy.service.MeetingService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.weaver.ast.Not;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
public class MeetingServiceImpl implements MeetingService {

    @Autowired
    private MeetingDao meetingDao;

    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<Meeting> findPage(int pageNum, int pageSize, String title, String status){
        PageHelper.startPage(pageNum, pageSize);
        if ("".equals(status)){
            status = null;
        }
        return new PageInfo<Meeting>(meetingMapper.findPage(title, status));
    }

    @Override
    public void save(Meeting meeting) {
        meetingDao.save(meeting);
    }

    @Override
    public Map<String, Object> findById(int id,int userId) {
        //根据id查询会议信息
        Meeting meeting = meetingDao.findById(id).get();
        //查询应到人数
        int deptUserCount = meetingDao.findById(id).get().getMakeUser().split(",").length;
        //查看已到人数
        int arrived = meetingMapper.findArrivedNum(meeting.getId());
        //未到人数
        int notArrived = deptUserCount - arrived;
        //查询登录用户是否有参加这个会议
        boolean isJoin = meetingMapper.findByUserIdAndMeetingId(userId,meeting.getId()) > 0;

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("meeting",meeting);
        resultMap.put("deptUserCount",deptUserCount);
        resultMap.put("arrivedNum",arrived);
        resultMap.put("notArrived",notArrived);
        resultMap.put("isJoin",isJoin);
        return resultMap;
    }

    @Override
    public String joinMeeting(int mid, int uid, boolean flag) {
        List<String> ids = Arrays.asList(meetingDao.findById(mid).get().getMakeUser().split(","));
        if (!ids.contains(mid+"")){
            return "您无权限操作此会议";
        }
        if (flag){
            //参加会议
            meetingMapper.join(uid, mid);
            return "参加会议成功";
        }else{
            meetingMapper.noJoin(uid,mid);
            return "取消会议成功";
        }
    }

}
